﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public class SkinnBoneArrayWizard : ScriptableWizard
    {
        public static SkinnBoneArrayWizard boneWizard = null;
        public static SkinnedMeshRenderer renderer = null;
        public static Vector2 scroll = Vector2.zero;

        public static void ShowBoneWizard(SkinnedMeshRenderer renderer)
        {
            SkinnBoneArrayWizard.renderer = renderer;
            boneWizard = DisplayWizard<SkinnBoneArrayWizard>(SkinnEx.EnforceObjectName(renderer) + " Bone Array");
        }

        private void OnEnable() { if (boneWizard & boneWizard != this) boneWizard.Close(); boneWizard = this; scroll = Vector2.zero; }
        private void OnWizardUpdate() { if (!renderer) { this.Close(); return; } helpString = ""; }

        private void OnGUI()
        {
            base.DrawWizardGUI();

            if (!renderer) { this.Close(); return; }
            var dirty = false;
            var bones = renderer.bones;
            if (!CanEditBones()) { EditorGUILayout.LabelField("no bones"); return; }

            scroll = EditorGUILayout.BeginScrollView(scroll);
            for (int i = 0; i < bones.Length; i++)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(i.ToString(), GUILayout.MaxWidth(50));
                EditorGUI.BeginChangeCheck();
                bones[i] = (Transform)EditorGUILayout.ObjectField(bones[i], typeof(Transform), true);
                if (EditorGUI.EndChangeCheck()) dirty = true;
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();

            if (dirty) { Undo.RecordObject(renderer, "Change Bone"); renderer.bones = bones; }

        }

        private static bool CanEditBones()
        {
            if (!renderer || !renderer.sharedMesh) return false;
            var sharedMesh = renderer.GetSharedMesh();
            int boneCount = SkinnEx.IsNullOrEmpty(sharedMesh.bindposes) ? 0 : sharedMesh.bindposes.Length;
            if (!SkinnEx.IsNullOrEmpty(renderer.bones, boneCount)) return true;
            if (boneCount < 1) return false;
            renderer.bones = new Transform[boneCount];
            return false;
        }
    }
}